#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/9/6 11:11
# @File           : __init__
# @IDE            : PyCharm
# @desc           : 描述

from typing import Any, List
from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession
from core.crud import DalBase
from . import models, schemas
from apps.check.sample.crud import SampleGroupDal

class ASRDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(ASRDal, self).__init__()
        self.db = db
        self.model = models.DCASR
        self.schema = schemas.ASRSimpleOut

    async def create_data(self, data: schemas.ASRIn, v_return_obj):
        asr = await self.get_data(asr_no=data.asr_no, v_return_none=True)
        if not asr:
            asr = await super().create_data(data, v_return_obj=True)
            lot_size, sample_size = None, None
            if data.quantity and data.quantity.isdigit():
                lot_size = int(data.quantity)
                group = await SampleGroupDal(self.db).get_group(group_name="ASR_Sampling", quantity=lot_size)
                if group: sample_size = group.value
                
            contents = [
                schemas.ASRContent(
                    asr_id=asr.id,
                    create_user="system",
                    lot_size=lot_size,
                    sample_size=sample_size,
                    accept_qty=sample_size,
                    insp_lot_no=data.lot_batch_no,
                    **item.model_dump()
                )
                for item in data.features
            ]
            await ASRContentDal(self.db).create_datas(contents)
            
        return await self.out_dict(asr, v_return_obj=v_return_obj)


    async def put_data(self, data_id: int, data: Any) -> Any:
        obj = await self.get_data(data_id=data_id)
        if obj.status == "检验中":
            for content in data.contents:
                await ASRContentDal(self.db).put_data(data_id=content.id, data=content)
        return await super().put_data(data_id=data_id, data=data)


class ASRContentDal(DalBase):
    def __init__(self, db: AsyncSession):
        super(ASRContentDal, self).__init__()
        self.db = db
        self.model = models.DCASRContent
        self.schema = schemas.ASRContent

    async def put_datas(self, ids: List[int], **kwargs):
        await self.db.execute(
            update(self.model).where(self.model.id.in_(ids)).values(
                **kwargs
            )
        )
        await self.flush()